package com.example.backend.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.entity.*;
import com.example.backend.mapper.*;
import com.example.backend.service.BookletService;
import com.example.backend.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 单词本相关服务实现
 * @author 李月
 * @date 2022/5/2 10:02
 */
@Component
public class BookletServiceImpl implements BookletService {
    @Autowired
    private BookletMapper bookletMapper;
    @Autowired
    private UserBookletMapper userBookletMapper;
    @Autowired
    private BookletEntryMapper bookletEntryMapper;
    @Autowired
    private EntryMapper entryMapper;
    @Autowired
    private CollectionMapper collectionMapper;
    @Autowired
    private CollectionBookletMapper collectionBookletMapper;
    @Autowired
    private SharedBookletMapper sharedBookletMapper;

    @Override
    public int createBooklet(int userId, String name, String introduction) {
        Booklet booklet = new Booklet();
        UserBooklet userBooklet = new UserBooklet();
        QueryWrapper<Booklet> wrapper = new QueryWrapper<>();
        wrapper.eq("booklet_name", name).eq("booklet_intro", introduction);
        if(!name.matches("^[a-zA-Z0-9_\u4e00-\u9fa5]{1,20}$")) {  //只含有汉字、数字、字母、下划线，下划线位置不限，长度1-20
            return 1;
        }

        if(introduction.length() > 100){    //简介长度不超过100
            return 2;
        }
        booklet.setBooklet_name(name);
        booklet.setBooklet_intro(introduction);
        Date date = new Date();
        Timestamp time = new Timestamp(date.getTime());
        booklet.setCreate_date(time);
        bookletMapper.insert(booklet);

        userBooklet.setUser_id(userId);
        userBooklet.setBooklet_id(booklet.getBooklet_id());
        userBookletMapper.insert(userBooklet);
        return 0;
    }

    @Override
    public PageUtils getBooklets(int userId, int page, int pageSize) {
        Page<BookletVO> p = new Page<>(page, pageSize);
        p.setRecords(this.bookletMapper.getBooklet(userId, p));
        return new PageUtils(p);
    }

    @Override
    public Map<String, Object> getBookletSpecification(int bookletId) {
        Map<String, Object> map = new HashMap<>();
        Booklet booklet = bookletMapper.selectById(bookletId);
        map.put("bookletName", booklet.getBooklet_name());
        map.put("bookletAuthor", userBookletMapper.getBookletAuthor(bookletId));
        map.put("bookletIntro", booklet.getBooklet_intro());
        map.put("bookletEntryCount", bookletEntryMapper.getEntryCount(bookletId));
        Date date = new Date(booklet.getCreate_date().getTime());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("bookletCreateDate", simpleDateFormat.format(date));
        map.put("bookletEntryLearnedCount", entryMapper.getEntryLearnedCount(bookletId));
        map.put("bookletEntryUnLearnedCount", bookletEntryMapper.getEntryCount(bookletId) - entryMapper.getEntryLearnedCount(bookletId));
        return map;
    }

    @Override
    public PageUtils getEntries(int bookletId, int page, int pageSize) {
        Page<EntryVO> p = new Page<>(page, pageSize);
        p.setRecords(this.entryMapper.getEntry(bookletId, p));
        return new PageUtils(p);
    }

    @Override
    public boolean modifyBooklet(int bookletId, String name, String introduction) {
        Booklet booklet = bookletMapper.selectById(bookletId);
        if(name == null || introduction == null) {
            return false;
        }
        booklet.setBooklet_name(name);
        booklet.setBooklet_intro(introduction);
        bookletMapper.updateById(booklet);

        Booklet updateBooklet = bookletMapper.selectById(bookletId);
        if(updateBooklet.getBooklet_name().equals(name) && updateBooklet.getBooklet_intro().equals(introduction)){
            return true;
        }
        return false;
    }

    @Override
    public boolean study(int bookletId, List<Map<String, Object>> list) {
        for(Map<String, Object> entry : list){
            int entryId = (int) entry.get("entryId");
            BookletEntry bookletEntry = bookletEntryMapper.getBookletEntry(bookletId, entryId);
            if(bookletEntry != null) {
                Entry updateEntry = entryMapper.selectById(entryId);
                updateEntry.setStudy_count((int) entry.get("studyCount"));
                updateEntry.setLast_study_datetime(java.sql.Date.valueOf((String) entry.get("lastStudyDatetime")));
                updateEntry.setRemark((String) entry.get("remark"));
                entryMapper.updateById(updateEntry);
            } else {
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean deleteEntry(int bookletId, List<Integer> entrylist) {
        for(Integer entryId : entrylist){
            BookletEntry bookletEntry = bookletEntryMapper.getBookletEntry(bookletId, entryId);
            if(bookletEntry != null) {
                bookletEntryMapper.deleteBookletEntry(bookletId, entryId);
            } else {
                return false;
            }
        }
        entryMapper.deleteBatchIds(entrylist);
        return true;
    }

    @Override
    public boolean deleteBooklet(int userId, int bookletId) {
        int oldBookletId = bookletId;
        if(collectionBookletMapper.getOldBooklet(bookletId) != null){
            oldBookletId = collectionBookletMapper.getOldBooklet(bookletId).getOld_booklet_id();
        }
        if(bookletMapper.selectById(bookletId) == null && bookletEntryMapper.getBookletCount(bookletId) == 0 && userBookletMapper.getUserBooklet(bookletId) == null && collectionMapper.getCollection(oldBookletId, userId) == null && collectionBookletMapper.getOldBooklet(bookletId) == null && sharedBookletMapper.getSharedBooklet(bookletId) == null)
            return false;
        List<Integer> entryList = bookletEntryMapper.getEntryId(bookletId);
        if(entryList.isEmpty() && collectionMapper.getCollection(oldBookletId, userId) == null){
            bookletMapper.deleteById(bookletId);
            userBookletMapper.deleteBooklet(bookletId);
            sharedBookletMapper.deleteSharedBooklet(bookletId);
        } else if(entryList.isEmpty() && collectionMapper.getCollection(oldBookletId, userId) != null){
            bookletMapper.deleteById(bookletId);
            userBookletMapper.deleteBooklet(bookletId);
            collectionMapper.deleteCollection(oldBookletId, userId);
            collectionBookletMapper.deleteCollectionBooklet(bookletId);
            sharedBookletMapper.deleteSharedBooklet(bookletId);
        } else if(!entryList.isEmpty() && collectionMapper.getCollection(oldBookletId, userId) != null){
            bookletEntryMapper.deleteBooklet(bookletId);
            bookletMapper.deleteById(bookletId);
            userBookletMapper.deleteBooklet(bookletId);
            entryMapper.deleteBatchIds(entryList);
            collectionMapper.deleteCollection(oldBookletId, userId);
            collectionBookletMapper.deleteCollectionBooklet(bookletId);
            sharedBookletMapper.deleteSharedBooklet(bookletId);
        } else {
            bookletEntryMapper.deleteBooklet(bookletId);
            bookletMapper.deleteById(bookletId);
            userBookletMapper.deleteBooklet(bookletId);
            entryMapper.deleteBatchIds(entryList);
            sharedBookletMapper.deleteSharedBooklet(bookletId);
        }

        if(bookletMapper.selectById(bookletId) == null && bookletEntryMapper.getBookletCount(bookletId) == 0 && userBookletMapper.getUserBooklet(bookletId) == null && collectionMapper.getCollection(bookletId, userId) == null && collectionBookletMapper.getOldBooklet(bookletId) == null && sharedBookletMapper.getSharedBooklet(bookletId) == null)
            return true;
        return false;
    }

    @Override
    public int addEntry(int bookletId, int wordId, String remark) {
        List<Integer> entryIdList = bookletEntryMapper.getEntryId(bookletId);
        for(int entryId : entryIdList){
            if(wordId == entryMapper.getWordId(entryId))
                return 1;
        }
        Entry entry = new Entry();
        entry.setEntry_word_id(wordId);
        entry.setRemark(remark);
        entry.setStudy_count(0);
        entry.setLast_study_datetime(java.sql.Date.valueOf("2022-05-01"));
        entry.setDeleted(0);
        entryMapper.insert(entry);

        BookletEntry bookletEntry = new BookletEntry();
        bookletEntry.setBooklet_id(bookletId);
        bookletEntry.setEntry_id(entry.getEntry_id());
        bookletEntryMapper.insert(bookletEntry);

        if(entryMapper.selectById(entry.getEntry_id()) != null && bookletEntryMapper.getBookletEntry(bookletId, entry.getEntry_id()) != null){
            return 0;
        }
        return 2;
    }

    @Override
    public List<Map<String, Object>> getTwentyWords(int bookletId) {
        List<WordVO> wordList = entryMapper.getTwentyWords(bookletId);
        List<Map<String, Object>> list = new ArrayList<>();
        for(WordVO word : wordList){
            Map<String, Object> map = new HashMap<>();
            map.put("entryId", word.getEntryId());
            map.put("studyCount", word.getStudyCount());
            map.put("wordSpell", word.getWordSpell());
            map.put("soundmark", word.getSoundmark());
            map.put("paraphrase", word.getParaphrase());
            map.put("remark", word.getRemark());
            list.add(map);
        }
        return list;
    }

}
